<template>
    <div class="profile-wrapper">
      <!-- 用户信息 -->
      <div class="profile-header">
        <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/api/upload-avatar"
            :data="{ userId: user.id }"
            :show-file-list="false"
            :on-success="handleAvatarChange"
            :before-upload="beforeAvatarUpload"
        >
            <img v-if="user.userAvatar" :src="user.userAvatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            <!-- <i v-else class="el-icon-plus avatar-uploader-icon"></i> -->
        </el-upload>
        <div class="info">
          <h2>{{ user.userName }}</h2>
          <div class="details">
            <span>  {{ user.major }} {{ user.grade }} {{ user.userClass }}班</span>
          </div>
          <div class="divider"></div>
        </div>
      </div>
  
      <!-- 主体表单区域 -->
      <el-row :gutter="20" class="form-row">
        <!-- 左侧：个人信息 -->
        <el-col :span="12">
          <el-card>
            <h3>个人信息</h3>
            <div class="divider"></div>
            <el-form label-position="top">
              <el-form-item label="账号">
                <el-input v-model="user.userAccount" :key="user.id" />
              </el-form-item>
              <el-form-item label="用户名">
                <el-input v-model="user.userName" :key="user.id"/>
              </el-form-item>
              <el-form-item label="电话号码">
                <el-input v-model="user.phoneNumber" :key="user.id">
                    <template #prefix>
                    <i class="fas fa-phone custom-icon"></i>
                    </template>
                </el-input>
              </el-form-item>
              <el-form-item label="专业">
                <el-input v-model="user.major" :key="user.id" />
              </el-form-item>
              <el-form-item label="年级">
                <el-input v-model="user.grade" :key="user.id"/>
              </el-form-item>
              <el-form-item label="班级">
                <el-input v-model="user.userClass" :key="user.id"/>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
  
        <!-- 右侧：密码修改 -->
        <el-col :span="12">
          <el-card>
            <h3>修改密码</h3>
            <div class="divider"></div>
            <el-form ref="passwordFormRef" label-position="top" :rules="rules" :model="passwordForm">
              <el-form-item label="旧密码" prop="oldPassword">
                <el-input type="password" v-model="passwordForm.originUserPassword" />
              </el-form-item>
              <el-form-item label="新密码" prop="newPassword">
                <el-input type="password" v-model="passwordForm.newUserPassword" />
              </el-form-item>
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input type="password" v-model="passwordForm.checkedNewUserPassword" />
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
      </el-row>
  
      <!-- 底部操作按钮 -->
      <div class="footer">
        <el-button type="primary" @click="handleSaveProfile">保存资料</el-button>
        <el-button @click="resetForm">重置</el-button>
      </div>
    </div>
  </template>
  
  <script setup >
  import { reactive, ref, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  
  // 导入自动生成的接口服务
  import { UserControllerService } from '../../../../generated/services/UserControllerService' // 根据你的项目路径调整
  import { useUserStore } from '../../../stores/user'
  
  // 用户信息对象
  const user = ref({
    id: null,
    userName: '',
    userAccount: '',
    phoneNumber: '',
    major: '',
    grade: '',
    userClass: '',
    userAvatar: '',
  })
  
  // 密码表单对象
  const passwordForm = ref({
    originUserPassword: '',
    newUserPassword: '',
    checkedNewUserPassword: '',
  })
  
  // 表单验证规则
  const rules = {
    originUserPassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
    newUserPassword: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
    checkedNewUserPassword: [
      { required: true, message: '请确认密码', trigger: 'blur' },
      {
        validator: (_, value) =>
          value === user.newUserPassword
            ? Promise.resolve()
            : Promise.reject('两次输入密码不一致'),
        trigger: 'blur'
      }
    ]
  }
  
  // 表单引用（用于触发验证）
  const passwordFormRef = ref()
  
  // 页面加载时获取当前用户信息
  onMounted(async () => {
    try {
      const response = await UserControllerService.getLoginUser()
      console.log('Response from getLoginUser:', response); 
      if (response.code === 0 && response.data) {
        const userData = response.data
        console.log('UserData:', userData); 
        user.value.id = userData.id
        user.value.userName = userData.userName
        user.value.userAccount = userData.userAccount
        user.value.phoneNumber = userData.phoneNumber
        user.value.major = userData.major
        user.value.grade = userData.grade
        user.value.userClass = userData.userClass
        user.value.userAvatar = userData.userAvatar || ''
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      ElMessage.error('获取用户信息失败')
    }
  })

  // 提交保存用户信息
  const handleSaveProfile = async () => {
    // 先验证密码一致性
    
    const valid = await passwordFormRef.value.validate().catch(() => false)
    if (!valid) return
  
    try {
      const payload = {
        id: user.value.id,
        userName: user.value.userName,
        userAccount: user.value.userAccount,
        phoneNumber: user.value.phoneNumber,
        major: user.value.major,
        grade: user.value.grade,
        userClass: user.value.userClass,
        userAvatar: user.value.userAvatar,
        originUserPassword: passwordForm.value.originUserPassword ,
        newUserPassword: passwordForm.value.newUserPassword ,
        checkedNewUserPassword: passwordForm.value.checkedNewUserPassword 
      }
      console.log("要提交的 payload:", payload)

      const response = await UserControllerService.editUser(payload)
  
      if (response.code === 0 && response.data === true) {
        ElMessage.success('资料更新成功！')
        resetForm()
        const userStore = useUserStore();
        userStore.fetchUserInfo()
      } else {
        ElMessage.error(response.message || '更新失败')
      }
    } catch (error) {
      console.error('更新失败:', error)
      ElMessage.error('更新失败，请检查网络或稍后再试')
    }
  }
  
  // 重置密码表单
  const resetForm = () => {
    passwordForm.value.originUserPassword = ''
    passwordForm.value.newUserPassword = ''
    passwordForm.value.checkedNewUserPassword = ''
  }
  
  // 头像上传前验证
  const beforeAvatarUpload = (file) => {
    const isImage = file.type.startsWith('image/')
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isImage) ElMessage.error('只能上传图片格式')
    if (!isLt2M) ElMessage.error('图片大小不能超过 2MB')
    return isImage && isLt2M
  }
  
  // 处理头像上传变更
  // 修改 handleAvatarChange 方法
 const handleAvatarChange = (response, uploadFile) => {
  if (response.code === 0 && response.data) {
    console.log('头像上传成功:', response.data)
    user.value.userAvatar = response.data; // 设置为后端返回的头像 URL
    ElMessage.success('头像上传成功！')
  } else {
    ElMessage.error(response.message || '头像上传失败')
  }
}

  </script>
  
  <style scoped>
.content::-webkit-scrollbar {
    display: none;
}

.profile-wrapper {
    display: flex;
    flex-direction: column;
    height: 100vh;
    padding: 20px;
    box-sizing: border-box;
    width: 100%;
    padding: 30px 20px;
    overflow-y: auto;
}

.profile-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    padding: 10px;
}

.avatar-uploader {
    width: 80px;
    height: 80px;
    border: 1px dashed #d9d9d9;
    border-radius: 50%;
    overflow: hidden;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 20px;
}

.avatar {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #999;
}

.info {
  display: flex;
  flex-direction: column;
}

.info h2 {
  margin: 0;
  font-size: 18px;
  color: #333;
  margin-left: 0px;
}

 .details span {
  font-size: 14px;
  color: #666;
  margin-top: 2px;
}

.divider {
  width: 100%;
  height: 2px;
  background-color: #ddd;
  margin: 5px 0;
}


.description {
    margin: 10px 0;
    color: #666;
}


.form-row {
    flex: 1;
    display: flex;
    justify-content: space-between;
}

.el-card {
    height: 100%;
    display: flex;
    flex-direction: column;
}

.el-form {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.footer {
    margin-top: 20px;
    text-align: right;
}


</style>